package com.rem.cloudalibaba.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rem.cloudalibaba.entity.CommonResult;
import com.rem.cloudalibaba.entity.Product;
import com.rem.cloudalibaba.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * 直接根据http 访问ip调用
 *
 * @author Rem
 * @date 2021-07-12
 */

@RestController
@RefreshScope
public class OrderController {

    @Autowired
    OrderService orderService;

    @Resource
    RestTemplate restTemplate;

    /**
     * 根据商品创建订单 使用restTemplate不做任何修改调用
     *
     * @param pid
     */
    @GetMapping("/ip/createOrder/{pid}")
    public CommonResult createOrder(@PathVariable("pid") Integer pid) {
        CommonResult<Product> result = restTemplate.getForObject("http://127.0.0.1:7001/product/getProduct/" + pid, CommonResult.class);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result));

        if (jsonObject.getInteger("code").equals(0)) {
            Product product = jsonObject.getObject("data", Product.class);
            orderService.createOrder(product);
            return CommonResult.ok();
        }
        return CommonResult.error();
    }


}
